package com.ls.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author Moro
 * @Date 2021/6/4 23:35
 * @title MyLB
 */
@Component
public class MyLB implements MyLoadBalancer {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int cur;
        int next;
        //自旋锁
        do {
            cur = this.atomicInteger.get();
            // 判断是否大于最大值
            //大于整型最大值则归零重新计数
            //
            next = cur >= 214783647 ? 0 : cur + 1;
            //进行CAS比较
        } while (!this.atomicInteger.compareAndSet(cur, next));
        System.out.println("*****next: " + next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        //获取访问第几个服务
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
